package exercise;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA
 * Description：ThreadPoolExecutor的优先级队列问题
 * User：chenshu
 * Date：2023-11-16
 * Time：19:33
 */
class CustomThreadFactory implements java.util.concurrent.ThreadFactory {
    private int count = 0;
    @Override
    public Thread newThread(Runnable r) {
        count++;
        System.out.println("创建线程：" + count);
        return new Thread(r);
    }
}
class Mytask implements Runnable, Comparable<Mytask> {

    int n;

    public Mytask(int n) {
        this.n = n;
    }

    @Override
    public int compareTo(Mytask o) {
        return (int) (this.n - o.n);
    }

    @Override
    public void run() {
        System.out.println("MyTask-" + n + "正在执行");
    }
}
public class Demo5 {
    public static void main(String[] args) {
        BlockingQueue<Runnable> queue = new PriorityBlockingQueue<>();
        ThreadPoolExecutor myThreadPool = new ThreadPoolExecutor(
                5,
                10,
                60,
                TimeUnit.SECONDS,
                queue,
                new CustomThreadFactory()
        );
        for (int i = 0; i < 10; i++) {
            //PriorityBlockingQueue不能使用submit
            myThreadPool.execute(new Mytask(i));
        }

    }
}
